<?php

class AuditableLog extends Doctrine_AuditLog
{

	private static $audit_columns = array('usuario', 'ip', 'fecha');

	public function __construct(array $options = array())
	{
		$this->_options['generateLog'] = true;
		parent::__construct($options);
	}

	public function setTableDefinition()
	{
		parent::setTableDefinition();

		if ($this->getOption('generateLog'))
		{
			$this->hasColumn(self::$audit_columns[0], 'string', 30, array('type' => 'string', 'length' => 30, 'notnull' => true));
			$this->hasColumn(self::$audit_columns[1], 'string', 20, array('type' => 'string', 'length' => 20, 'notnull' => true));
			$this->hasColumn(self::$audit_columns[2], 'timestamp', null, array('type' => 'timestamp'));
		}
	}

	public function isAuditable()
	{
		$name = $this->_options['table']->getComponentName();

		$q = Doctrine_Query::create()
			->from('AuditoriaEntidad')
			->select('auditable')
			->where('entidad = ?', $name)
			->fetchArray();

		if (isset($q[0]))
			return $q[0]['auditable'];
		return false;
	}
	
	public function generateClassFromTable(Doctrine_Table $table)
	{
		if (sfContext::hasInstance())
			parent::generateClassFromTable($table);

		return false; //evita que se generen formularios y filtros para la version
	}

	public static function getAuditColumnNames() //sgeModelGenerator
	{
		return self::$audit_columns;
	}

	public static function getVersionClassName($model)
	{
		return $model . 'Version';
	}

	public static function getVersionTableName($model)
	{
		return sfInflector::underscore($model) . '_version';
	}

	public static function formatColumnNames($columns, $alias)
	{
		$fields = '';
		foreach ($columns as $name)
		{
			$fields = $fields . sprintf('{%s.%s}', $alias, $name);
		}

		return $fields;
	}

}
